//
//  HomeAllCheckVC.m
//  Ginix
//
//  Created by fzq on 2025/2/24.
//

#import "HomeAllCheckVC.h"
#import "ALLProgressView.h"
#import "HomeCheckBar.h"
#import "AllCheckAnimationView.h"
#import "HomeCamerView.h"
#import "HealthComInfoVC.h"

@interface HomeAllCheckVC ()<HomeCamerDelegate>
@property (nonatomic,strong) UILabel * infoLabel;
@property (nonatomic,strong) UIButton * enterBtn;
@property (nonatomic,strong) UILabel * descLabel;
@property (nonatomic,strong) ALLProgressView * progressView;
@property (nonatomic,strong) HomeCheckBar * checkBar;
@property (nonatomic,strong) UIImageView * iconView;
@property (nonatomic,strong) UILabel * tipsLabel;
@property (nonatomic,strong) AllCheckAnimationView * anView;
@property (nonatomic,strong) HomeCamerView * camerView;
@property (nonatomic,assign) NSInteger q2;
@property (nonatomic,assign) NSInteger heart;
@property (nonatomic,assign) NSInteger heartRota;
@property (nonatomic,assign) CGFloat  temp;
@end

@implementation HomeAllCheckVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setSubViewLayout];
}
-(void)setSubViewLayout{
    
    self.title = @"全面检测";
    self.navgationView.infoLabel.textColor = RDRGB(0x714933);
    
    [self.view addSubview:self.infoLabel];
    [self.view addSubview:self.descLabel];
    [self.view addSubview:self.enterBtn];
    [self.view addSubview:self.progressView];
    [self.view addSubview:self.iconView];
    [self.view addSubview:self.checkBar];
    [self.view addSubview:self.tipsLabel];
    [self.view addSubview:self.anView];
    [self.view addSubview:self.camerView];
           
}

-(void)enterBtnAction:(UIButton *)sender{
    
    @WeakObj(self)
    [[BCLRingManager shared] getBlcConnectWithCompletion:^(BOOL state) {
        FHideLoding
        if (!state) {
            FhudShowStr(@"设备未连接");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                id vc = [[NSClassFromString(@"HomeJoinVC") alloc]init];
                [[UIViewController findNavigationController] pushViewController:vc
                                                                       animated:YES];
            });
        }else{
            
            [self.camerView startCamer];
            if ([sender.titleLabel.text isEqual:@"开始检测"]) {
                self.tipsLabel.text = @"请保持戒指在左手手指不要取下...";
                self.enterBtn.enabled = NO;
                self.enterBtn.alpha = 0.8;
                [self.anView startAnimation];
                [self requestHeart:^(NSInteger value) {
                    self.heart = value;
                        [self requestHrv:^(NSInteger value) {
                            @StrongObj(self)
                            self.heartRota = value;
                                [self.progressView setIndex:1];
                                [self.anView setSecondStyle];
                                [sender setTitle:@"下一步" forState:UIControlStateNormal];
                                self.tipsLabel.text = @"请将戒指佩戴在右手手指";
                                self.iconView.image = [UIImage imageNamed:@"Home_all_check_right_icon"];
                                self.enterBtn.enabled = YES;
                                self.enterBtn.alpha = 1;
                        }];
                }];
            }
            if ([sender.titleLabel.text isEqual:@"下一步"]) {
                self.enterBtn.enabled = NO;
                self.enterBtn.alpha = 0.8;
                self.tipsLabel.text = @"请保持戒指在右手手指不要取下...";
                [self.anView startAnimation];
                    [self requestOxy:^( NSInteger value) {
                        self.q2 = value;
                            [self requestBody:^( float value) {
                                @StrongObj(self)
                                self.temp = value;
                                    [self.progressView setIndex:2];
                                    [self.anView stopAnimation];
                                    self.enterBtn.enabled = YES;
                                    self.enterBtn.alpha = 1;
                                    [self.enterBtn setTitle:@"舌象拍照" forState:UIControlStateNormal];
                            }];
                    }];
            }
            if ([sender.titleLabel.text isEqual:@"舌象拍照"]) {
                [UIView animateWithDuration:1 animations:^{
                    self.iconView.hidden = YES;
                    self.checkBar.hidden = YES;
                    self.tipsLabel.hidden = YES;
                    self.anView.hidden = YES;
                    self.enterBtn.hidden = YES;
                    self.descLabel.hidden = YES;
                    self.camerView.hidden = NO;
                }];
            }
        }
    }];   
}

-(void)requestHeart:(void(^)(NSInteger value))respone{
    @WeakObj(self)
    [[BCLRingManager shared] startHeartRateMeasurementWithRrTime:20 progress:^(double progress) {
        @StrongObj(self)
        [self updateTotalProgressWithMethodIndex:1 andProgress:progress * 100];
    } rrData:^(NSInteger sequence, NSInteger count, NSArray<NSNumber *> * _Nonnull data) {
        
    } heartRate:^(NSInteger value) {
        
    } completion:^(BOOL success, NSInteger value) {
        @StrongObj(self)
        if (!success) {
            FhudShowStr(@"心率检测失败，请佩戴好戒指之后重新检测")
            [self reloadFirstCheckType];

        }else{
            !respone?:respone(value);
        }
    }];
}

-(void)requestHrv:(void(^)(NSInteger value))respone{
    @WeakObj(self)
    [[BCLRingManager shared] startHRVMeasurementWithProgress:^(double progress) {
        @StrongObj(self)
        [self updateTotalProgressWithMethodIndex:2 andProgress:progress * 100];
        } waveData:^(NSInteger sequence, NSInteger count, NSArray<NSNumber *> * _Nonnull data) {
            
        } completion:^(BOOL success, NSInteger value) {
            if (!success) {
                FhudShowStr(@"HRV检测失败，请佩戴好戒指之后重新检测")
                [self reloadFirstCheckType];
                
            }else{
                !respone?:respone(value);
            }
        }];
}
-(void)reloadFirstCheckType{
    
    [self.progressView setIndex:1];
    [self.anView stopAnimation];
    self.enterBtn.enabled = YES;
    self.enterBtn.alpha = 1;
    [self updateTotalProgressWithMethodIndex:1 andProgress:0];
    [self.enterBtn setTitle:@"开始检测" forState:UIControlStateNormal];
    
}

-(void)requestOxy:(void(^)(NSInteger value))respone{
    @WeakObj(self)
    [[BCLRingManager shared] startO2MeasurementWithProgress:^(double progress) {
        @StrongObj(self)
        [self updateTotalProgressWithMethodIndex:1 andProgress:progress * 100];

        } waveData:^(NSInteger sequence, NSInteger count, NSArray<NSNumber *> * _Nonnull data) {
            
        } completion:^(BOOL success, NSInteger value) {
            if (!success) {
                FhudShowStr(@"血氧测量失败，请佩戴好戒指之后重新检测")
                [self reloadSecondCheckType];
            }else{
                !respone?:respone(value);
            }
        }];
}

-(void)requestBody:(void(^)(float value))respone{
    @WeakObj(self)
    [[BCLRingManager shared] readTemperatureWithCompletion:^(BOOL success, float temperature) {
        @StrongObj(self)
        if (success) {
            [self updateTotalProgressWithMethodIndex:3 andProgress:1];
            !respone?:respone(temperature);
        }else{
            FhudShowStr(@"体温测量失败，请佩戴好戒指之后重新检测")
            [self reloadSecondCheckType];
        }
    }];
}

-(void)reloadSecondCheckType{
    
    [self.progressView setIndex:1];
    [self.anView stopAnimation];
    self.enterBtn.enabled = YES;
    self.enterBtn.alpha = 1;
    [self updateTotalProgressWithMethodIndex:2 andProgress:0];
    [self.enterBtn setTitle:@"下一步" forState:UIControlStateNormal];
    
}



- (void)updateTotalProgressWithMethodIndex:(NSInteger)index andProgress:(float)progress {
    float singleMethodProgress = progress / 2.0;
    float totalProgress = 0.0;
    switch (index) {
        case 1:
            totalProgress = singleMethodProgress;
            break;
        case 2:
            totalProgress = 50 + singleMethodProgress;
            break;
        case 3:
            totalProgress = 100;
            break;
        default:
            break;
    }
    self.checkBar.progress = totalProgress;
}

-(void)getImageUrl:(NSString *)imge{
    @WeakObj(self)
    NSDictionary * parm = @{@"heart":@(self.heart),@"heartRota":@(self.heartRota),@"q2":@(self.q2),@"temp":@(self.temp),@"images":imge};
    [SPNetworkingIns POST:PORT(@"bh-center/api/invite/ComprehensiveTesting") params:parm success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject, NSInteger code) {
        @StrongObj(self)
        HomeAllCheckModel * model = [HomeAllCheckModel yy_modelWithDictionary:responseObject[@"data"]];
        HealthComInfoVC * vc = [[HealthComInfoVC alloc]init];
        vc.ID = model.ID;
        [self.navigationController pushViewController:vc animated:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:RefshAllDataNotification object:nil];
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}


-(UILabel *)infoLabel{
    
        if (!_infoLabel) {
        _infoLabel = [[UILabel alloc]initWithFrame:CGRectMake((WIDTH - 320 * FMScaleX) / 2, NavHeight + 20 * FMScaleX, 320 * FMScaleX, 40 * FMScaleX)];
        _infoLabel.font = Regular(14);
        _infoLabel.textColor = RDRGB(0x714933);
        _infoLabel.numberOfLines = 0;
        _infoLabel.text = @"为了能让检测准确度更高，请您按照以下步骤、根据提示操作：";
    }
    return _infoLabel;
}
-(UILabel *)descLabel{
    
    if (!_descLabel) {
        _descLabel = [[UILabel alloc]initWithFrame:CGRectMake((WIDTH - 330 * FMScaleX) / 2, HEIGHT - kSafeAreaHeight - 80 * FMScaleX, 330 * FMScaleX, 75 * FMScaleX)];
        _descLabel.textColor = RDRGB(0xD54A43);
        _descLabel.text = @"注意事项： 为了检测数据更准确，请尽量在清晨空腹开始操作，不要做剧烈运动，奶茶、咖啡、烟酒等兴奋物质将会影响数据精准。";
        _descLabel.numberOfLines = 0;
        _descLabel.font = Medium(15);
    }
    return _descLabel;
}
-(UIButton *)enterBtn{
    
    if (!_enterBtn) {
        _enterBtn = [[UIButton alloc]initWithFrame:CGRectMake((WIDTH - 130 * FMScaleX) /2 , HEIGHT - kSafeAreaHeight - 130 * FMScaleX, 130 * FMScaleX, 40 * FMScaleX)];
        [_enterBtn setBackgroundImage:[UIImage imageNamed:@"Home_all_check_btn"] forState:UIControlStateNormal];
        [_enterBtn setTitle:@"开始检测" forState:UIControlStateNormal];
        [_enterBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_enterBtn addTarget:self action:@selector(enterBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _enterBtn;
}

-(ALLProgressView *)progressView{

    if (!_progressView) {
        _progressView =[[ ALLProgressView alloc]initWithFrame:CGRectMake(20 * FMScaleX, GETMaxY(self.infoLabel) + 20 * FMScaleX, WIDTH - 40 * FMScaleX, 50 * FMScaleX)];
    }
    return _progressView;
}

-(UIImageView *)iconView{
    
    if (!_iconView) {
        _iconView = [[UIImageView alloc]initWithFrame:CGRectMake(20 * FMScaleX, GETMaxY(self.progressView) + 10 * FMScaleX, 80 * FMScaleX, 90* FMScaleX)];
        _iconView.image = [UIImage imageNamed:@"Home_all_check_left_icon"];
    }
    return _iconView;
}

-(HomeCheckBar *)checkBar{
    
    if(!_checkBar){
        _checkBar = [[HomeCheckBar alloc]initWithFrame:CGRectMake(GETMaxX(self.iconView) + 20 * FMScaleX, GETMaxY(self.progressView) + 26 * FMScaleX, 234 * FMScaleX, 40 * FMScaleX)];
    }
    return _checkBar;
}

-(UILabel *)tipsLabel{
    
    if (!_tipsLabel) {
        _tipsLabel = [[UILabel alloc]initWithFrame:CGRectMake(GETMaxX(self.iconView) + 20 * FMScaleX, GETMaxY(self.checkBar) + 6 * FMScaleX, 200 * FMScaleX, 20 * FMScaleX)];
        _tipsLabel.font = Regular(13 * FMScaleX);
        _tipsLabel.textColor = RDRGB(0xAD7D62);
        _tipsLabel.text = @"请将戒指佩戴在左手手指上";
    }
    return _tipsLabel;
}
-(AllCheckAnimationView *)anView{
    
    if (!_anView) {
        _anView = [[AllCheckAnimationView alloc]initWithFrame:CGRectMake((WIDTH - 100 * FMScaleX) / 2, GETMaxY(self.tipsLabel) + 20 * FMScaleX, 100 * FMScaleX, 240 * FMScaleX)];
    }
    return _anView;
}
-(HomeCamerView *)camerView{
    
    if (!_camerView) {
        _camerView = [[HomeCamerView alloc]initWithFrame:CGRectMake(0, GETMaxY(self.progressView) , WIDTH, HEIGHT - kSafeAreaHeight - 130 * FMScaleX - NavHeight - 50 * FMScaleX)];
        _camerView.backgroundColor = UIColor.clearColor;
        _camerView.hidden = YES;
        _camerView.delegate = self;
    }
    return _camerView;
}
@end
